<template>
    <div>
        <Table :columns="columns" :paginatedData="paginatedData" :btnList="btnList" :btnListTable="btnListTable"
            :isFixedColumn="true" :columnWidth="230" :isMore="false" :footerBtnList="footerBtnList"
            :isEndColumns="false" :tableLoading="loading" :total="total" @pageSize="handlePageSize" @handle-order="setOrder"
            @currentPage="handleCurrentPage">
            <!-- 条件组,插槽 -->
            <template #default>
                <el-form :inline="true" :model="formBtnList" class="demo-form-inline" @submit.native.prevent>
                    <!-- <el-form-item label="用户账号:">
              <el-input v-model="formBtnList.user" placeholder="请输入用户账号" />
            </el-form-item>
            <el-form-item label="用户名称:">
              <el-input v-model="formBtnList.name" placeholder="请输入用户名称" />
            </el-form-item> -->
                    <el-form-item label="">
                        <el-select v-model="formBtnList.lang" placeholder="请选择语言" style="width: 240px"
                            @change="handleOnSelect">
                            <el-option v-for="item in languageOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="">
                        <el-input v-model="formBtnList.search" :prefix-icon="Search" placeholder="请输入产品名称" />
                    </el-form-item>
                </el-form>
            </template>
        </Table>

        <!-- 弹窗 -->
        <DialogCom ref="dialogCom" :dialogVisible="dialogVisible" :btnLoading="btnLoading" :tableTitle="tableTitle"
            :formData="formData" :ruleForm="ruleForm" :rules="rules" @beforeClose="beforeClose"
            @dialogSwitch="dialogSwitch" @submitForm="submitForm" />

        <seriesMentDialog ref="dialogCom" :dialogVisible="dialogVisible2" :btnLoading="btnLoading2" :ruleForm="ruleForm"
            :tableTitle="tableTitle2" :titleIDText="titleIDText" @beforeClose="beforeClose" @submitForm="submitForm">
        </seriesMentDialog>
    </div>
</template>

<script setup lang='ts' name="seriesMent">
import { ref, reactive, onMounted } from 'vue'
import type { FormRules } from 'element-plus'
import Table from '@/components/Table.vue';
import seriesMentDialog from './seriesMentDialog.vue';
import DialogCom from '@/components/DialogCom.vue';
import { products, productsAdd, productsEdit, productsDel, productsDetail, productsStatus,productOrder } from '@/api/seriesMent/index.ts'
import { require } from '@/utils/require';
import { Search } from '@element-plus/icons-vue'
import { useRouteStore } from '@/stores/modules/counter.ts'
const routeStore = useRouteStore();
// 表格相关 开始
const loading = ref(false)
const titleIDText = ref('')

// 表头数据
const columns = ref([
    { prop: 'product_key', label: '产品key', width: 160 },
    { prop: 'product_name', label: '产品名称', width: 200 },
    // { prop: 'product_desc', label: '产品描述', width: 250 },
    { prop: 'admin_name', label: '添加人', width: 160 },
    { prop: 'language', label: '语言', width: 120, formatter: (row: any) => row.language == 'cn' ? '中文' : row.language == 'en' ? '英文' : '' },
    { prop: 'updated_time', label: '修改时间', width: '', },
    { prop: 'cover', label: '封面', width: 150, uploadAvatar: true },
    { prop: 'order', label: '权重排序', width: 120,order:true },
    { prop: 'status', label: '上架状态', width: 130, formatter: (row: any) => row.status == '1' ? '已上架' : '已下架' },
]);
// 表格数据
let paginatedData = ref([]);
// 查询条件
const formBtnList = reactive({
    // lang: 'cn',
    lang: routeStore.seriesMentLang ? routeStore.seriesMentLang : 'cn',
    search: '',
    page_size: 10,
    page: 1,
})
let languageOptions = ref([
    {
        value: 'cn',
        label: '中文',
    },
    {
        value: 'en',
        label: '英文',
    },
])
let languageOptions2 = ref(languageOptions.value)
const total = ref(0)

// 查询按钮
const handInquire = () => {
    loading.value = true
    products(formBtnList, 'cn').then((res: any) => {
        if (res.code === 200) {
            total.value = res.data.total
            if (res.data.total === 0) {
                ElMessage.error(`产品信息不存在`)
                paginatedData.value = []
                return
            }
            const processedData = res.data.products.map((item: Object) => {
                return {
                    ...item,
                    judData: item.status  // 添加 judData 属性，并赋值为 status
                };
            });
            paginatedData.value = processedData
            // paginatedData.value = res.data.products
        } else {
            ElMessage.error(`产品信息不存在`)
            total.value = 0
            paginatedData.value = []
        }
    }).catch((error: any) => {
        ElMessage.error(`请求错误: ${error.msg}`)
        total.value = 0
        paginatedData.value = []
    }).finally(() => {
        loading.value = false
    })
}
const handleOnSelect = () => {
    routeStore.setSeriesMentLang(formBtnList.lang)// pinia 存储语言状态
    handInquire()
}
interface RuleForm {
    product_name: string
    product_desc: string
}
// 表单数据
// const ruleForm = reactive({})
let ruleForm = ref([{ lang: '中文', product_name: '', status: '0' }, { lang: '英文', product_name: '', status: '0' }])
// 重置表单方法
const resetForm = (initialData?: Partial<RuleForm>) => {
    // Object.assign(ruleForm, {
    //     product_id: '',
    //     product_name: '',
    //     status: '',
    //     ...(initialData || {}),
    // });
    ruleForm.value = [{ lang: '中文', product_name: '', status: '0' }, { lang: '英文', product_name: '', status: '0' }]
    if (initialData) {
        btnLoading2.value = true
        productsDetail(initialData.product_key).then((res: any) => {
            if (res.code === 200) {
                ruleForm.value = res.data.products
                ruleForm.value.forEach(item => {
                    if (!('status' in item) || item.status === '') {
                        item.status = '0';
                    }
                });
                if (ruleForm.value.length === 1 && res.data.products[0].language === 'cn') {
                    ruleForm.value.push({ lang: 'en', product_name: '', status: '0' })
                } else if (ruleForm.value.length === 1 && res.data.products[0].language === 'en') {
                    ruleForm.value.unshift({ lang: 'cn', product_name: '', status: '0' })
                }
                ruleForm.value[0].lang = '中文'
                ruleForm.value[1].lang = '英文'
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).finally(() => {
            btnLoading2.value = false
        })
    }
};
// 新增
const handAddAccount = () => {
    resetForm();
    tableTitle2.value = '新增产品'
    dialogVisible2.value = true
    // tableTitle.value = '新增产品'
    // dialogVisible.value = true
}
// 编辑
const handEditAccount = (row: object, index: number) => {
    titleIDText.value = row.product_key.toString()
    resetForm(row);
    tableTitle2.value = '编辑产品'
    dialogVisible2.value = true
}
const setOrder = (i: any, row: any)=>{
    ElMessageBox.prompt('请输入目标顺序（数字越大排序越靠后）', {
    confirmButtonText: '提交',
    cancelButtonText: '取消',
    inputType: 'number', // 限制为数字输入
    inputPattern: /^[1-9]\d*$/, // 正整数校验（从1开始，避免0或负数）
    inputErrorMessage: '请输入有效的正整数（不能为空）',
  })
    .then(({ value }) => {
      // 二次校验：确保值不为空且为数字（兼容可能的类型转换问题）
      const orderNum = Number(value);
      if (!orderNum || isNaN(orderNum)) {
        ElMessage.error('排序值不能为空且必须为有效数字');
        return;
      }
      // 调用排序接口
      productOrder({product_id:String(row.product_id),order:row.order,target_order:orderNum}).then((res) => {
        if(res.code === 200){
            ElMessage.success(`排序已更新为：${orderNum}`);
            // 刷新列表
            handInquire();
        }else{
            ElMessage.error(res.msg);
        }
      }).catch(() => {
        ElMessage.error('排序更新失败');
      });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消排序设置',
      });
    });
} 
// 重置 查询条件
const handDerived = () => {
    formBtnList.lang = 'cn'
    formBtnList.search = ''
    handInquire()
}
// 按钮组
const btnList = [
    { name: '查询', type: 'primary', click: handInquire, icon: '' },
    { name: '重置', type: 'success', click: handDerived, icon: '' },
]
const footerBtnList = [
    { name: '新增', type: 'primary', click: handAddAccount, icon: '' },
]
// 删除
const deleteData = (row: object, index: number) => {
    // console.log(111, row.product_id, index);
    ElMessageBox.confirm(
        '确定删除此项吗？',
        '删除',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    ).then(() => {
        productsDel(row.product_key).then((res: any) => {
            if (res.code === 200) {
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
        }).finally(() => {
            handInquire()
        })
    })
}
// 表单控件数据
let formData = reactive([
    { type: 'input', label: '产品名称', prop: 'product_name', span: 24, placeholder: '请输入' },
    { type: 'input', label: '产品描述', prop: 'product_desc', span: 24, placeholder: '请输入' },
])
// 新增名称
// const handAddName = (row: object, index: number) => {
//     resetForm(row);
//     tableTitle.value = '新增名称'
//     if (formBtnList.lang) {
//         const targetValue = formBtnList.lang;
//         const targetOption = languageOptions2.value.find(option => option.value === targetValue);
//         if (targetOption) {
//             languageOptions2.value.forEach(option => {
//                 option.disabled = false;
//             });
//             targetOption.disabled = true;
//         }
//     }
//     formData = [
//         { type: 'input', label: '名称', prop: 'name', span: 24, placeholder: '请输入' },
//         { type: 'select', label: '语言', prop: 'lang', span: 24, placeholder: '请输入', options: languageOptions2.value },
//     ]
//     dialogVisible.value = true
// }
// 上架
const listed = (row: object, index: number) => {
    ElMessageBox.confirm(
        '是否上架?',
        '上架',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    )
        .then(() => {
            let para = {
                product_id: row.product_id?.toString(),
                status: '1',
            }
            productsStatus(para).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        message: '成功',
                        type: 'success',
                    })
                } else {
                    ElMessage.error(`请求错误: ${res.msg}`)
                }
            }).catch((error: any) => {
                ElMessage.error(`请求错误: ${error.msg}`)
            }).finally(() => {
                handInquire()
            })
        })
        .catch(() => {

        })
}
// 下架
const removed = (row: object, index: number) => {
    ElMessageBox.confirm(
        '是否下架?',
        '下架',
        {
            confirmButtonText: '是',
            cancelButtonText: '否',
            type: 'warning',
        }
    )
        .then(() => {
            let para = {
                product_id: row.product_id?.toString(),
                status: '0',
            }
            productsStatus(para).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        message: '成功',
                        type: 'success',
                    })
                } else {
                    ElMessage.error(`请求错误: ${res.msg}`)
                }
            }).catch((error: any) => {
                ElMessage.error(`请求错误: ${error.msg}`)
            }).finally(() => {
                handInquire()
            })
        })
        .catch(() => {

        })
}
// 操作列按钮组
const btnListTable = ref([
    { name: '上架', type: 'primary', click: listed, judgment: true, isShow: ['0'], },
    { name: '下架', type: 'warning', click: removed, judgment: true, isShow: ['1'], },
    { name: '编辑', type: 'success', click: handEditAccount },
    { name: '删除', type: 'danger', click: deleteData },
    // { name: '新增名称', type: 'primary', click: handAddName },
])
// 分页事件触发
const handlePageSize = (page_size: number) => {// 每页大小
    // console.log('handlePageSize', page_size);
    formBtnList.page_size = page_size
    handInquire()
};
const handleCurrentPage = (page: number) => {// 页码
    // console.log('handleCurrentPage', page);
    formBtnList.page = page
    handInquire()
};
// 表格相关 结束

// 弹窗相关
const dialogCom = ref<InstanceType<typeof DialogCom>>();
const btnLoading = ref(false)
const btnLoading2 = ref(false)
// 表单校验配置
const rules = reactive<FormRules<RuleForm>>({
    product_name: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    product_desc: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    lang: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '此项为必填项', trigger: 'blur' },
    ],
})
interface SimplifiedRuleFormItem {
    product_id: string;
    product_name: string;
    status: string;
}
// 弹窗 确认按钮
const submitForm = ((ruleFormData: any, tableTitle: string) => {
    // console.log(111, ruleFormData, tableTitle);
    // let para = {
    //     ...ruleFormData,
    //     lang: 'cn',
    // }
    if (tableTitle === '新增产品') {
        btnLoading2.value = true
        productsAdd({ products: ruleFormData }).then((res: any) => {
            if (res.code === 200) {
                if (dialogCom.value) {
                    dialogCom.value.cancelClick(); // 调用子组件方法
                }
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
                btnLoading2.value = false
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
        }).finally(() => {
            btnLoading2.value = false
            handInquire()
        })
    } else if (tableTitle === '编辑产品') {
        btnLoading2.value = true
        const simplifiedData = ref<SimplifiedRuleFormItem[]>(
            ruleFormData.map(item => ({
                product_id: item.product_id?.toString(),
                product_name: item.product_name,
                status: item.status,
            }))
        )
        productsEdit({ products: simplifiedData.value }).then((res: any) => {
            if (res.code === 200) {
                if (dialogCom.value) {
                    dialogCom.value.cancelClick(); // 调用子组件方法
                }
                ElMessage({
                    message: '成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(`请求错误: ${res.msg}`)
                btnLoading2.value = false
            }
        }).catch((error: any) => {
            ElMessage.error(`请求错误: ${error.msg}`)
        }).finally(() => {
            btnLoading2.value = false
            handInquire()
        })
    }
})
// 标题
const tableTitle = ref('');
const dialogVisible = ref(false);
const tableTitle2 = ref('');
const dialogVisible2 = ref(false);
const beforeClose = () => {
    titleIDText.value = ''
    dialogVisible.value = false;
    dialogVisible2.value = false;
}
const dialogSwitch = (row: object) => {
    console.log('row: ', row);

}
onMounted(() => {
    handInquire()
})
</script>
<style lang='scss' scoped>
.demo-form-inline {
    .el-input {
        width: 265px;

    }

    :deep(.el-input__wrapper) {
        border-radius: 20px;
    }

}
</style>